package cn.zhoujing.demo.jwt.config;

import cn.hutool.core.collection.ListUtil;
import cn.zhoujing.demo.jwt.enity.MyUser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author zhoujing
 * @createTime 2023/11/19 - 14:20
 */
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable()
                .authorizeRequests()
                .anyRequest().permitAll()
                .and()
                .formLogin()
                .and()
                .logout();
    }


    @Bean
    @Override
    public UserDetailsService userDetailsService() {

        return (username) -> {
            if (username.equals("user")) {
                MyUser myUser = new MyUser();
                myUser.setUserName("user");
                myUser.setPassword(passwordEncoder().encode("user"));
                myUser.setAuthorities(ListUtil.of(() -> "user"));
                myUser.setEnabled(true);
                myUser.setAccountNonLocked(true);
                myUser.setAccountNonExpired(true);
                myUser.setCredentialsNonExpired(true);
                return myUser;
            } else if (username.equals("admin")) {
                MyUser myUser = new MyUser();
                myUser.setUserName("admin");
                myUser.setPassword(passwordEncoder().encode("admin"));
                myUser.setAuthorities(ListUtil.of(() -> "admin"));
                myUser.setEnabled(true);
                myUser.setAccountNonLocked(true);
                myUser.setAccountNonExpired(true);
                myUser.setCredentialsNonExpired(true);
                return myUser;
            }
            return null;
        };
    }


}
